<template>
  <a-drawer
    :title="$t('message.Authorized_user')"
    :visible="visible"
    width="650px"
    :closable="true"
    @close="close"
    :maskClosable="true"
  >
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('message.User_Accounts')">
              <a-input
                :placeholder="$t('message.Please_enter')"
                v-model="queryParam.username"
                allowClear
                @pressEnter="searchQuery"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <span
              style="float: left; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <a-button type="primary" @click="searchQuery" icon="search">{{
                $t("message.Search")
              }}</a-button>
            </span>
            <span
              style="float: right; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <a-button @click="handleAddUserRole" type="primary" icon="plus">{{
                $t("message.Bind_the_user")
              }}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <!--    <a-dropdown style="margin-bottom: 16px;" v-if="selectedRowKeys.length > 0">-->
    <!--      <a-menu slot="overlay">-->
    <!--        <a-menu-item key="1" @click="batchDel">-->
    <!--          <a-icon type="delete"/>-->
    <!--          取消关联-->
    <!--        </a-menu-item>-->
    <!--      </a-menu>-->
    <!--      <a-button>批量操作-->
    <!--        <a-icon type="down"/>-->
    <!--      </a-button>-->
    <!--    </a-dropdown>-->
    <!-- table区域-begin -->
    <div>
      <a-table
        style="height: 500px"
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="action" slot-scope="text, record">
          <a-popconfirm
            :title="$t('message.Are_you_sure_to_cancel_the_association') + '?'"
            @confirm="() => handleDelete(record.id)"
          >
            <a>{{ $t("message.Unassociation") }}</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <select-user-modal
      ref="selectUserModal"
      @selectFinished="selectUserFinished"
    ></select-user-modal>
  </a-drawer>
</template>
<script>
import { getAction, postAction, deleteAction } from "@/api/manage";
import SelectUserModal from "./OrgSelectUserModal.vue";

export default {
  name: "RoleUserModal",
  components: {
    SelectUserModal,
  },
  data() {
    return {
      visible: false,
      roleId: "",
      roleName: "",
      loading: false,
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      selectedRowKeys: [],
      selectionRows: [],
      /* 数据源 */
      dataSource: [],
      isorter: {
        column: "createTime",
        order: "desc",
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "30"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      columns: [
        {
          title: this.$t("message.User_Accounts"),
          align: "center",
          dataIndex: "username",
        },
        {
          title: this.$t("message.User_name"),
          align: "center",
          dataIndex: "realname",
        },
        {
          title: this.$t("message.Handle"),
          dataIndex: "action",
          align: "center",
          width: 120,
          scopedSlots: { customRender: "action" },
        },
      ],
      url: {
        list: "/orgRole/userList",
        delete: "/orgRole/deleteUser",
        addUserRole: "orgUser/saveRoleUser",
        deleteUserRoleBatch: "/orgUser/deleteUserRoleBatch",
        deleteUserRole: "/orgUser/deleteUserRole",
      },
    };
  },
  created() {},
  methods: {
    init(roleId, roleName) {
      this.roleId = roleId;
      this.roleName = roleName;
      this.loadData();
    },
    close() {
      this.reset();
      this.$emit("close");
      this.visible = false;
    },
    reset() {
      this.selectedRowKeys = [];
      this.queryParam = {};
    },
    handleAddUserRole() {
      if (this.currentRoleId == "") {
        this.$message.error(this.$t("message.Please_choose_a_role") + "!");
      } else {
        this.$refs.selectUserModal.visible = true;
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    searchQuery() {
      this.loadData(1);
    },
    searchReset() {
      this.queryParam = {};
      this.loadData(1);
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc";
      }
      this.ipagination = pagination;
      this.loadData();
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    loadData() {
      this.loading = true;
      const params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        roleId: this.roleId,
        username: this.queryParam.username,
      };
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result;
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleDelete(id) {
      if (!this.url.deleteUserRole) {
        this.$message.error(
          this.$t("message.Please_set_the_url_delete2_attribute") + "!"
        );
        return;
      }
      var that = this;
      deleteAction(that.url.deleteUserRole, {
        roleId: that.roleId,
        userId: id,
      }).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },

    // batchDel() {
    //   if (!this.url.deleteBatch2) {
    //     this.$message.error('请设置url.deleteBatch2属性!')
    //     return
    //   }
    //   if (this.selectedRowKeys2.length <= 0) {
    //     this.$message.warning('请选择一条记录！')
    //     return
    //   } else {
    //     var ids = ''
    //     for (var a = 0; a < this.selectedRowKeys2.length; a++) {
    //       ids += this.selectedRowKeys2[a] + ','
    //     }
    //     var that = this
    //     console.log(this.currentDeptId)
    //     this.$confirm({
    //       title: '确认取消关联',
    //       content: '是否删除选中数据?',
    //       onOk: function () {
    //         deleteAction(that.url.deleteBatch2, {roleId: that.currentRoleId, userIds: ids}).then((res) => {
    //           if (res.success) {
    //             that.$message.success(res.message)
    //             that.loadData2()
    //             that.onClearSelected()
    //           } else {
    //             that.$message.warning(res.message)
    //           }
    //         })
    //       }
    //     })
    //   }
    // },

    selectUserFinished(data) {
      let params = {};
      params.roleId = this.roleId;
      params.userIdList = [];
      for (var a = 0; a < data.length; a++) {
        params.userIdList.push(data[a]);
      }
      console.log(params);
      postAction(this.url.addUserRole, params).then((res) => {
        if (res.success) {
          this.$message.success(res.message);
          this.loadData();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped></style>